<template>
  <div class="operationPage">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="点位搜索：">
        <el-input v-model="dianweiValue" clearable placeholder="请输入" />
      </el-form-item>
      <el-form-item label="区域搜索：">
        <el-select v-model="areaName" clearable placeholder="请输入">
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="searchDianwei"
        >查询</el-button>
      </el-form-item>
    </el-form>

    <div class="table">
      <el-row>
        <el-button
          icon="el-icon-circle-plus-outline"
          class="add"
          type="primary"
          @click="addDianwei"
        >新建</el-button>

      </el-row>
      <el-table row-key="id" :border="false" :data="tableList" style="width: 100%;">
        <el-table-column
          label="序号"
          width="80"
          type="index"
        />
        <el-table-column
          prop="name"
          label="点位名称"
          width="220"
        />
        <el-table-column
          prop="region.name"
          label="所在地区"
          width="220"
        />
        <el-table-column
          prop="businessType.name"
          label="商圈类型"
          width="160"
        />
        <el-table-column prop="ownerName" label="合作商" width="160" />
        <el-table-column prop="addr1" label="详细地址" width="280" />
        <el-table-column label="操作" width="260">
          <template v-slot="{ row }">
            <el-button
              size="mini"
              type="text"
              @click="getDesc(row.id)"
            >查看详情</el-button>
            <el-button
              size="mini"
              type="text"
              @click="getChange(row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              style="color:red"
              @click="del(row.id)"
            >删除</el-button>
          </template></el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pagination-container">
        <span class="pageText">共{{ totalCount }}条记录 第 {{ pageIndex }}/{{
          totalPage
        }}
          页</span>
        <el-pagination
          background:true
          layout="prev, pager, next"
          prev-text="上一页"
          next-text="下一页"
          :total="+totalCount"
          @prev-click="prevPage"
          @next-click="nextPage"
        />
      </div>

    </div>
    <!-- 新建弹层 -->
    <el-dialog
      title="新增点位"
      :visible.sync="isShowDialog"
      width="40%"
      class="dialog"
      @close="close"
    >
      <el-form ref="xiugaiForm" :model="xiugaiForm" label-width="120px" class="addDialog">
        <el-form-item prop="name" label="点位名称:">
          <el-input
            v-model="xiugaiForm.name"
            placeholder="请输入"
            maxlength="15"
            show-word-limit
            style="width: 80%"
            @input="shebeibianhao"
          />
        </el-form-item>
        <el-form-item prop="region.name" label="所在区域:">
          <el-select v-model="xiugaiForm.region.name" style="width: 80%" clearable placeholder="请输入">
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="businessType.name" label="所属商圈:">
          <el-select v-model="xiugaiForm.businessType.name" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in shangquan"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商:" prop="ownerName">
          <el-select v-model="xiugaiForm.ownerName" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in guishu"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="详细地址" prop="addr">
          <el-cascader
            v-model="xiugaiForm.selectedOptions"
            style="width:80%"
            size="large"
            :options="options"
          />
          <!-- @change="handleChange" -->
        </el-form-item>
        <el-form-item label="" prop="addr1">
          <el-input
            v-model="xiugaiForm.addr1"
            placeholder="请输入详细地址"
            maxlength="40"
            show-word-limit
            type="textarea"
            :rows="4"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item>
          <!-- <template #footer :center="true"> -->
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button @click="close">取消</el-button>
              <el-button class="enter" @click="xiugaiBtn">确定</el-button>
            </el-col>
          </el-row>
          <!-- </template> -->
        </el-form-item>
      </el-form>
      <!-- 补货内层 -->
      <el-dialog
        class="neicengbuhuo"
        width="40%"
        :visible.sync="buhuoDialog"
        append-to-body
      >
        <template #title><span class="title">补货详情</span></template>
        <el-table
          :data="buhuoList"
          height="360"
          style="width: 100%"
        >
          <el-table-column
            prop="channelCode"
            label="货道编号"
            width="170"
          />
          <el-table-column
            prop="sku.skuName"
            label="商品名称"
            width="170"
          />
          <el-table-column
            prop="currentCapacity"
            label="当前数量"
          />
          <el-table-column
            prop="address"
            label="还可添加"
          >
            <template v-slot="{ row }">
              <span>{{ address = parseInt(row.maxCapacity) - parseInt(row.currentCapacity) }}</span>
            </template></el-table-column>
          <el-table-column
            prop="maxCapacity"
            label="补满数量"
          >
            <template v-slot="{ row }">
              <span>{{ maxCapacity = parseInt(row.maxCapacity) - parseInt(row.currentCapacity) }}</span>
            </template></el-table-column>
        </el-table>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button>取消</el-button>
            <el-button class="enter1" @click="addGongdan">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </el-dialog>
    <!-- ⭐查看点位详情 -->
    <el-dialog
      center
      class="neiceng"
      width="50%"
      :visible.sync="descListDialog"
      append-to-body
    >
      <template #title><span class="titlepeizhi">点位详情</span></template>
      <el-table
        :data="descList"
        max-height="550"
        :border="false"
        style="width: 100%"
      >
        <el-table-column
          prop="date"
          label="序号"
          width="180"
          type="index"
        />
        <el-table-column
          prop="innerCode"
          label="机器编码"
          width="180"
        />
        <el-table-column
          prop="vmStatus"
          label="设备状态"
        >
          <template v-slot="{ row }">
            <span v-if="row.vmStatus === 0">未投放</span>
            <span v-else-if="row.vmStatus === 1">运营</span>
            <span v-else-if="row.vmStatus === 3">撤机</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="lastSupplyTime"
          label="最后一次供货时间"
        />
      </el-table>
    </el-dialog>

    <!-- 查看工单详情 -->
    <el-dialog width="40%" class="gongdanDetail" :visible.sync="outerVisible" center>
      <template #title><span class="title">工单详情</span></template>
      <div class="pic">
        <div class="naozhong">
          <img v-if="gongdanzhaungtai==='待办'" src="" alt="">
          <img v-else-if="gongdanzhaungtai==='取消'" src="" alt="">
          <img v-else src="" alt="">
        </div>
        <span class="tou">{{ gongdanzhaungtai }}</span>
        <img v-if="gongdanzhaungtai==='待办'" src="https://likede2-admin.itheima.net/img/pic_1.834b274c.png" alt="">
        <img v-else-if="gongdanzhaungtai==='取消'" src="https://likede2-admin.itheima.net/img/pic_3.e8208e34.png" alt="">
        <img v-else src="https://likede2-admin.itheima.net/img/pic_4.3b5af41c.png" alt="">
      </div>
      <div class="txt">
        <ul>
          <li><span>设备编号:</span><span>{{ xiangqingList.innerCode }}</span></li>
          <li><span>运营人员:</span><span>{{ xiangqingList.userName }}</span></li>
          <li><span>工单方式:</span><span v-if="xiangqingList.createType">手动</span><span v-else>自动</span></li>
        </ul>
        <ul>
          <li><span>创建日期:</span><span>{{ xiangqingList.createTime }}</span></li>
          <li><span>工单类型:</span><span>{{ gongdanLeixing }}</span></li>
          <li><span>备注:</span><span>{{ xiangqingList.desc }}</span></li>
          <li><span>补货数量:</span><el-button type="text" class="demo" @click="buhuoDetail">补货详情</el-button></li>
        </ul>
      </div>
      <!-- 判断工单状态 -->

      <template #footer :center="true">
        <el-button v-if="gongdanzhaungtai==='待办'" class="btn" @click="innerVisible = true">取消工单</el-button>
        <el-button v-if="gongdanzhaungtai ==='取消'" class="btn" @click="addChongxin">重新创建</el-button>
      </template>
      <!-- 内层 -->
      <el-dialog
        center
        class="neiceng"
        width="30%"
        title="取消工单后，将不能恢复，是否确认取消？"
        :visible.sync="innerVisible"
        append-to-body
      >
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="getGongdanquxiao">确定</el-button>
        </div>
      </el-dialog>

    </el-dialog>
    <!-- 查看详情--补货详情 -->
    <el-dialog
      class="chakanbuhuo"
      width="40%"
      :visible.sync="chakanbuhuoDialog"
      append-to-body
    >
      <template #title><span class="title">补货详情</span></template>
      <el-table
        :data="chakanbuhuoList"
        height="360"
        style="width: 100%"
      >
        <el-table-column
          prop="channelCode"
          label="货道编号"
          width="290"
        />
        <el-table-column
          prop="skuName"
          label="商品"
          width="290"
        />
        <el-table-column
          prop="expectCapacity"
          label="补货数量"
          width="90"
        />
      </el-table>
    </el-dialog>
    <!-- 补货警戒 -->
    <el-dialog
      center
      class="neiceng"
      width="30%"
      :visible.sync="buhuojingjieDialog"
      append-to-body
    >
      <template #title><span class="titlepeizhi">工单配置</span></template>
      <span class="spanjingjie">补货警戒线:</span>
      <el-input-number v-model="alertValue" class="shezhijingjieInput" controls-position="right" :min="1" :max="100" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="buhuojingjieDialog = false">取 消</el-button>
        <el-button class="enter1" @click="getJingjieshezhi">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 省市区联动
import { regionData } from 'element-china-area-data'
import { getArea, searchDianwei, addDianwei, getDesc, getDeldianwei, getTable, getShangquan, getGuishu, getxiugaidianwei } from '@/api/node'
import { getJingjiezhi, getJingjieshezhi, getBuhuoqingdan, getOperation, getBuhuoDesc, getzhuangtaiList, addOperation, getYunWeiRen, getGongdanList, getGongdanDesc, getGongdanquxiao } from '@/api/task'
export default {
  name: 'Operation',
  data() {
    return {
      // 搜索
      dianweiValue: '',
      // 详情
      descListDialog: false,
      descList: [],
      // 地区所有数据
      options: regionData,
      // 表单渲染地区数据
      selectedOptions: ['110000', '110100', '110114'],
      shangquan: [],
      guishu: [],
      // 新建&修改弹层
      type: '',
      xiugaiForm: {
        name: '',
        region: {
          name: ''
        },
        businessType: {
          name: ''
        },
        ownerName: '',
        addr: '',
        addr1: '',
        regionId: '',
        ownerId: ''
      },
      isShowDialog: false,
      // table
      tableList: [],
      region: {},
      businessType: {},
      // 搜索
      areaName: '',
      areaList: [],
      pageIndex: 1,
      pageSize: 10,
      // 补货警戒
      buhuojingjieDialog: false,
      // 警戒值
      alertValue: null,
      // 查看补货-右边
      chakanbuhuoDialog: false,
      chakanbuhuoList: [],
      // 补货内层弹框
      buhuoDialog: false,
      buhuoList: [],
      // 搜索
      taskCode: '',
      statusName: null,
      // 状态列表
      zhuangtaiList: [],
      // 查看详情弹层
      outerVisible: false,
      innerVisible: false,
      xiangqingList: [],
      gongdanLeixing: '',
      gongdanzhaungtai: '',
      list: [],
      totalCount: null,
      totalPage: '',
      isRepair: true,
      addValue: {
        // 创建类型
        createType: 1,
        // 设备编号
        innerCode: '',
        // 执行人id
        userId: null,
        // 工单类型
        productType: null,
        // 描述信息
        desc: '',
        // 防止数据发布不成功
        assignorId: null
      },
      // 运维人员
      yunweirenyuan: [],
      // 工单类型
      gongdanList: []
    }
  },
  created() {
    // 获取区域⭐
    this.getArea()
    // 获取table数据
    this.getTable()
    // ⭐

    this.getyunyingList()
    // 状态列表
    this.getzhuangtaiList()
  },
  methods: {
    // 搜索
    async searchDianwei() {
      const res = await searchDianwei({ pageIndex: 1, pageSize: 10, name: this.dianweiValue, regionId: this.areaName })
      this.tableList = res.currentPageRecords
    },
    // 新建
    async addDianwei() {
      this.type = 'add'
      this.isShowDialog = true
      const res = await getShangquan()
      console.log(res)
      this.shangquan = res
      const res2 = await getGuishu()
      this.guishu = res2.currentPageRecords
    },
    // 获取详情
    async getDesc(id) {
      const res = await getDesc(id)
      this.descList = res.map(item => {
        item.lastSupplyTime = item.lastSupplyTime.replace('T', ' ')
        return item
      })
      console.log(res)
      this.descListDialog = true
    },
    // 删除点位
    async  del(id) {
      await getDeldianwei(id)
      this.$message.success({
        message: '删除点位成功',
        offset: 90
      })
      this.getTable()
    },
    handleChange(value) {
      // 拿到地区的最后一层数据（value代表所有code）
      console.log(value.at(-1))
      console.log(this.selectedOptions)
      // 三级联动的数据
      console.log(this.options)
    },
    // 关闭修改弹层
    close() {
      this.isShowDialog = false
      // this.selectedOptions = []
      // this.$nextTick(() => {
      //   this.$refs.xiugaiForm.resetFields()
      // })
      this.xiugaiForm = {
        name: '',
        region: {
          name: ''
        },
        businessType: {
          name: ''
        },
        ownerName: '',
        addr: '',
        addr1: '',
        regionId: '',
        ownerId: ''
      }
    },
    // 修改确认
    async xiugaiBtn() {
      const obj = {
        name: this.xiugaiForm.name,
        addr: this.xiugaiForm.addr1,
        areaCode: this.xiugaiForm.selectedOptions[2],
        createUserId: 63,
        regionId: this.areaList.filter(item => item.name === this.xiugaiForm.region.name)[0].id,
        businessId: this.shangquan.filter(item => item.name === this.xiugaiForm.businessType.name)[0].id,
        ownerName: this.xiugaiForm.ownerName,
        ownerId: +this.guishu.filter(item => item.name === this.xiugaiForm.ownerName)[0].id
      }
      if (this.type === 'xiugai') {
        const id = this.xiugaiForm.id
        console.log(obj)
        try {
          await getxiugaidianwei(obj, id)
          this.$message.success({
            message: '修改点位成功',
            offset: 90
          })
          this.isShowDialog = false
          this.getTable()
        } catch (error) {
          this.$message.warning({
            message: error.response.data,
            offset: 90
          })
        }
      } else {
        try {
          await addDianwei(obj)
          this.$message.success({
            message: '新增点位成功',
            offset: 90
          })
          this.isShowDialog = false
          this.getTable()
        } catch (error) {
          this.$message.warning({
            message: error.response.data,
            offset: 90
          })
        }
      }
    },
    // 修改
    async  getChange(row) {
      this.type = 'xiugai'
      if (row.areaCode === '110100') {
        this.xiugaiForm.selectedOptions = ['110000', '110100', '110114']
      } else {
        await this.$set(this.selectedOptions, 2, row.areaCode)
        await this.$set(this.selectedOptions, 1, parseInt(row.areaCode / 100) + '00')
        await this.$set(this.selectedOptions, 0, parseInt(row.areaCode / 10000) + '0000')
      }
      // this.getArea()
      const res = await getShangquan()
      console.log(res)
      this.shangquan = res

      const res2 = await getGuishu()
      this.guishu = res2.currentPageRecords
      console.log(this.guishu)
      this.isShowDialog = true
      this.xiugaiForm = JSON.parse(JSON.stringify(row))
      console.log(row)
      this.xiugaiForm.selectedOptions = this.selectedOptions
      console.log(this.xiugaiForm)
    },
    // 获取table数据
    async getTable() {
      const res = await getTable({ pageIndex: this.pageIndex, pageSize: this.pageSize })
      console.log(res)
      this.tableList = res.currentPageRecords
      this.tableList = this.tableList.filter(item => {
        item.addr1 = item.addr.split('-').at(-1)
        return item
      })
      // console.log(this.tableList)
      this.totalCount = res.totalCount
      this.totalPage = res.totalPage
    },
    // 获取区域⭐
    async getArea() {
      const res = await getArea({ pageIndex: this.pageIndex, pageSize: 10000 })
      this.areaList = res.currentPageRecords
    },
    // ⭐
    // 设置警戒值
    async getJingjieshezhi() {
      const res = await getJingjieshezhi({ alertValue: this.alertValue })
      if (res) {
        this.buhuojingjieDialog = false
        this.$message.success({
          message: '设置警戒值成功',
          offset: 90
        })
      }
    },
    // 补货警戒
    async jingjie() {
      const num = await getJingjiezhi()
      this.alertValue = num
      this.buhuojingjieDialog = true
    },
    // 补货详情
    async buhuoDetail() {
      const res = await getBuhuoDesc(this.xiangqingList.taskId)
      this.chakanbuhuoList = res
      this.chakanbuhuoDialog = true
    },
    // 补货内层弹框
    async buhuo() {
      this.buhuoDialog = true
      const res = await getBuhuoqingdan('01000034')
      this.buhuoList = res
    },
    // 状态列表
    async getzhuangtaiList() {
      const res = await getzhuangtaiList()
      this.zhuangtaiList = res
    },
    async getyunyingList() {
      // 获取运营工单数据列表A
      const res = await getOperation({
        pageIndex: this.pageIndex,
        pageSize: 10
        // isRepair: false
      })
      this.list = res.currentPageRecords.map(item => {
        item.createTime = item.createTime.replace('T', ' ')
        item.updateTime = item.updateTime.replace('T', ' ')
        return item
      })
      this.pageIndex = res.pageIndex
      this.pageSize = res.pageSize
      // this.totalCount = res.totalCount
      // this.totalPage = res.totalPage
    },
    async onSubmit() {
      const obj = {
        taskCode: this.taskCode,
        pageIndex: this.pageIndex,
        pageSize: 10,
        isRepair: true,
        status: this.statusName
      }
      const res = await getOperation(obj)
      this.list = res.currentPageRecords.map(item => {
        item.createTime = item.createTime.replace('T', ' ')
        item.updateTime = item.updateTime.replace('T', ' ')
        return item
      })
      this.pageIndex = res.pageIndex
      this.pageSize = res.pageSize
      // this.totalCount = res.totalCount
      // this.totalPage = res.totalPage
    },
    // 切换上分页
    prevPage() {
      if (this.pageIndex !== 1) {
        this.pageIndex--
        this.getTable()
      }
    },
    // 下一页
    nextPage() {
      if (this.totalPage > this.pageIndex) {
        this.pageIndex++
        this.getTable()
      } else {
        this.pageIndex = this.totalPage
      }
    },
    // 新建弹层
    async addItem() {
      this.getGongdanList1()

      this.isShowDialog = true
    },
    async shebeibianhao() {
      if (this.addValue.innerCode) {
        const res = await getYunWeiRen(this.addValue.innerCode)
        this.yunweirenyuan = res
      }
    },
    // 获取工单类型
    async getGongdanList1() {
      const res = await getGongdanList()
      this.gongdanList = res.filter(item => item.type === 1)
    },
    // 添加工单
    async addGongdan() {
      this.addValue.assignorId = this.addValue.userId
      const res = await addOperation(this.addValue)
      if (res) {
        this.isShowDialog = false
        this.$refs.addForm.resetFields()
        this.getyunyingList()
        this.$message.success({
          message: '创建工单成功',
          offset: 90
        })
        this.addValue = {}
      } else {
        this.isShowDialog = false
      }
      this.yunweirenyuan = []
    },
    // 工单详情
    async getGongdanDesc(row) {
      this.outerVisible = true
      const obj = {
        // taskName: '运维工单',
        createType: 1,
        innerCode: row.innerCode,
        userId: row.userId,
        assignorId: row.assignorId,
        productType: row.taskType.taskType,
        desc: row.desc
      }
      const res = await getGongdanDesc(row.taskId, obj)
      // console.log(res)
      this.xiangqingList = res
      this.gongdanLeixing = this.xiangqingList.taskType.typeName
      this.gongdanzhaungtai = this.xiangqingList.taskStatusTypeEntity.statusName
    },
    // 取消工单
    async getGongdanquxiao() {
      const obj = {
        taskId: this.xiangqingList.taskId,
        desc: this.xiangqingList.desc
      }
      await getGongdanquxiao(this.xiangqingList.taskId, obj)
      this.innerVisible = false
      this.outerVisible = false
      this.getyunyingList()
      this.$message.success({
        message: '取消工单成功',
        offset: 90
      })
    },
    // 重新创建
    addChongxin() {
      this.shebeibianhao()
      this.outerVisible = false
      this.isShowDialog = true
      this.addValue = this.xiangqingList
      this.addValue.productType = this.gongdanLeixing
    }
  }
}
</script>
 <style lang="scss">
 *{
  margin: 0;
  padding: 0;
 }
li{
list-style: none;
}
</style>

<style lang="scss" scoped>
.neiceng{
  // margin-top: 250px;
}
.gongdanDetail{
  display: flex;
flex-direction: column;
  .txt{
  // background-color: #1554b4;
  display: flex;
  justify-content: space-between;
  align-items: center;
  li{
    margin-top: 20px;
  }
}
.pic{
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f8f8;
  height: 70px;
  line-height: 70px;
  .naozhong{
   img{
    margin-top: 35px;
    padding-left: 15px;
   }
  }
  .tou{
    position: relative;
    left: -250px;
    top:3px
  }
}
.el-button{
  background-color: #fdf6ec;
  border: 0;
}
.title{
  float: left;
}
}

::v-deep .operationPage{
  font-size: 28px;
}
.demo-form-inline {
  background-color: #fff;
  height: 64px;
  display: flex;
  .el-form-item {
    margin-top: 13px;
    margin-left: 13px;
    .el-button {
      background-color: #5f84ff;
    }
  }
}
.table {
  margin-top: 26px;
  background-color: #fff;
  padding-left: 13px;
  padding-top: 20px;
  .add {
    color: #fff;
    background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
    border: 0;
  }
  .peizhi {
    background-color: #fdf6ec;
    border: 0;
    color: #121212;
  }
  .el-table {
    // background-color: #1554b4;
  }
}
.has-gutter {
  background-color: rgb(11, 95, 231);
}
::v-deep .btn-prev {
  width: 70px;
  height: 32px;
  background-color: #d5ddf8;
  border-radius: 2px;
}
::v-deep .btn-next {
  width: 70px;
  height: 32px;
  background-color: #d5ddf8;
  border-radius: 2px;
  margin-left: 15px;
}
.pagination-container{
  height: 100px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 100px;
}
::v-deep .pageText{
  font-size: 18px;
  color: #dbdfe5;
  margin-left: 15px;
}
.addDialog{
  .enter{
    color: #fff;
    background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
    border: 0;
  }
}
.bhqd{
  color: #5f84ff;
}
::v-deep .demo{
  background-color: #fff !important;
}
.enter1{
     color: #fff;
    background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
    border: 0;
}
.titlepeizhi{
  float: left;
}
.spanjingjie{
  margin-right: 15px;
}
.shezhijingjieInput{
  width: 80%;
}
::v-deep .el-pager{
  display: none;
}
</style>
